new 做了什么
js
function myNew(context, ...args) {
var obj = {};
obj.__proto__ = context.prototype;
// var obj = Object.create(context.prototype)
const result = context.call(obj, ...args);
return result instanceof Object ? result : obj;
}
new return
返回基本类型
- 不影响
js
function Animate (name) {
this.name = name
return 'hello'
}
const cat = new Animate('xiaobao');
// cat.name === xiaobao
返回对象类型
- 有影响,实例等于 return 返回的对象
js
function Animate (name) {
this.name = name
return {}
}
const cat = new Animate('xiaobao');
// cat 是 {}
构造函数和普通函数
- 调用方式: 使用 new 关键字的函数,为构造函数
- 大小写:首字母大小写,构造函数大些
- this 指向:构造函数指向实例本身,普通函数 非严格模式为 window